<template>
  <div class="container">
    <el-scrollbar class="user">
      <div class="label-out">{{ $t('企业信息设置') }}</div>
      <div class="form">
        <!-- 使用 $t 函数翻译标签 -->
        <div class="label">{{ $t('logo配置') }}</div>
        <el-upload class="user-upload" :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false"
                   :auto-upload="true" :on-success="handleUploadSuccess" :on-error="handleUploadError"
                   accept="image/jpeg, image/png, image/gif, image/bmp, image/webp" :before-upload="beforeUpload">
          <img v-if="avatarUrl" :src="avatarUrl" alt="" class="avatar"/>
          <div v-else class="avatar-upload"></div>
        </el-upload>
      </div>
      <div class="form">
        <!-- 使用 $t 函数翻译带星号的标签 -->
        <div class="label"><span class="require">*</span>{{ $t('企业名称配置') }}</div>
        <div class="user-input">
          <!-- 使用 $t 函数翻译输入框占位符 -->
          <el-input v-model="companyname" :placeholder="$t('请输入企业名称')"/>
        </div>
      </div>
      <div class="divider"></div>
      
      <div class="label-out" style="margin-bottom: 20px;">{{ $t('平台设置') }}</div>
      <div class="form">
        <!-- 使用 $t 函数翻译带星号的标签 -->
        <div class="label"><span class="require">*</span>{{ $t('平台选择') }}</div>
        <div class="user-input">
          <!-- 使用 $t 函数翻译选择框占位符 -->
          <el-select v-model="aiPlatform" :placeholder="$t('请选择平台')" size="large" style="width: 413px;" clearable
                     @change="handlePlatformChange">
            <el-option v-for="item in platforms" :key="item.aiPlatform" :label="item.aiPlatformLabel"
                       :value="item.aiPlatform"/>
          </el-select>
        </div>
      </div>
      <div class="form">
        <div class="label"><span class="require">*</span>{{ $t('平台配置') }}</div>
        <div class="user-input">
          <el-input type="textarea" v-model="aiPlatformParams" style="width: 413px;"></el-input>
        </div>
      </div>
      <div class="form">
        <!-- 使用 $t 函数翻译带星号的标签 -->
        <div class="label"><span class="require">*</span>{{ $t('模型选择（多选）') }}</div>
        <div class="user-input">
          <!-- 使用 $t 函数翻译选择框占位符 -->
          <el-select v-model="selectedModels" :placeholder="$t('请选择模型')" size="large" style="width: 413px;"
                     clearable multiple
                     :disabled="!aiPlatform">
            <el-option v-for="item in models" :key="item.id" :label="item.modelName" :value="item.id">
              <span style="float: left">【{{ item.modelTypeLabel }}】{{ item.modelAlias }}</span>
            </el-option>
          </el-select>
        </div>
      </div>
      <div v-if="!companyId">
        <div class="label-out" style="margin-bottom: 20px;">{{ $t('账号分配') }}</div>
        <div class="form progress">
          <div class="label">
            <div class="dot active"></div>
            <!-- 使用 $t 函数翻译标签 -->
            <span class="require">*</span><span>{{ $t('管理员账号') }}</span>
          </div>
          <div class="user-input">
            <!-- 使用 $t 函数翻译输入框占位符 -->
            <el-input v-model="adminusername" :placeholder="$t('请输入管理员账号')"/>
          </div>
        </div>
        <div class="form progress">
          <div class="label">
            <div class="dot active"></div>
            <!-- 使用 $t 函数翻译标签 -->
            <span class="require">*</span><span>{{ $t('初始密码') }}</span>
          </div>
          <div class="user-input">
            <!-- 使用 $t 函数翻译输入框占位符 -->
            <el-input v-model="adminpassword" :placeholder="$t('请输入初始密码')"/>
          </div>
        </div>
        <div class="form progress">
          <div class="label">
            <div class="dot active"></div>
            <!-- 使用 $t 函数翻译标签 -->
            <span class="require">*</span><span>{{ $t('确认密码') }}</span>
          </div>
          <div class="user-input">
            <!-- 使用 $t 函数翻译输入框占位符 -->
            <el-input v-model="confirmpwd" :placeholder="$t('请输入确认密码')"/>
          </div>
        </div>
        <div class="form progress">
          <div class="label">
            <div class="dot"></div>
            <!-- 使用 $t 函数翻译标签 -->
            <span class="require">*</span><span>{{ $t('管理员姓名') }}</span>
          </div>
          <div class="user-input">
            <!-- 使用 $t 函数翻译输入框占位符 -->
            <el-input v-model="adminname" :placeholder="$t('请输入管理员姓名')"/>
          </div>
        </div>
        <div class="form progress">
          <div class="label">
            <div class="dot"></div>
            <!-- 使用 $t 函数翻译标签 -->
            <span class="require">*</span><span>{{ $t('管理员手机号') }}</span>
          </div>
          <div class="user-input">
            <!-- 使用 $t 函数翻译输入框占位符 -->
            <el-input v-model="adminmobile" :placeholder="$t('请输入请填写管理员手机号')"/>
          </div>
        </div>
        <div class="form progress">
          <div class="label">
            <div class="dot"></div>
            <!-- 使用 $t 函数翻译标签 -->
            <span class="require">*</span><span>{{ $t('管理员邮箱') }}</span>
          </div>
          <div class="user-input">
            <!-- 使用 $t 函数翻译输入框占位符 -->
            <el-input v-model="adminemail" :placeholder="$t('请输入管理员邮箱')"/>
          </div>
        </div>
        <div class="form progress">
          <div class="label">
            <div class="dot no-line"></div>
            <!-- 使用 $t 函数翻译标签 -->
            <span style="padding-left: 12px;">{{ $t('信息备注') }}</span>
          </div>
          <div class="user-input">
            <!-- 使用 $t 函数翻译输入框占位符 -->
            <el-input v-model="remark" :placeholder="$t('请输入信息备注')"/>
          </div>
        </div>
      </div>
      
      <el-button type="primary" size="large" @click="submitForm">{{ $t('提交') }}</el-button>
      
      <!--      <div class="api-key" v-if="companyId">
              <div class="label-out" style="margin-bottom: 10px;">{{ $t('API Key管理') }}</div>
              <el-button type="primary" plain :icon="Delete" style="margin-bottom: 20px" @click="deleteSome">{{ $t('删除') }}</el-button>
              <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column property="aiPlatformLabel" :label="$t('名称')" />
                <el-table-column property="apikey" :label="$t('API key')" />
                <el-table-column property="createDate" :label="$t('创建时间')" />
                <el-table-column :label="$t('操作')" width="100">
                  <template #default="scope">
                    <div class="actions">
                      <span class="iconfont icon-shanchu" @click="deleteItem"></span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <div class="pagination" v-if="total > 0">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                               :page-sizes="[100, 200, 300, 400]" :size="size" :disabled="disabled" :background="background"
                               layout="prev, pager, next" :total="total" @size-change="handleSizeChange"
                               @current-change="handleCurrentChange" />
                <span class="total">{{ $t('共') }}{{ total }}{{ $t('条') }}</span>
              </div>
            </div>-->
    </el-scrollbar>
  </div>
</template>

<script>
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';
import {
  addCompany,
  companyInfo,
  companyModels,
  deleteSysWnApikey,
  editCompany,
  getAiPlatformConf,
  getAiPlatformList,
  getSysWnApikey
} from '@/api/index'
import {Delete, Plus} from '@element-plus/icons-vue';

export default {
  name: 'AddCompany',
  data() {
    return {
      uploadUrl: `${process.env.VUE_APP_BASE_API}sys/oss/upload`,
      uploadHeaders: {
        Token: `${localStorage.getItem('token')}`,
      },
      Plus,
      Delete,
      total: null,
      currentPage: 1,
      pageSize: 20,
      size: 'default',
      disabled: false,
      background: true,
      tableData: [],
      selectedItems: [],
      avatarUrl: '',
      companyname: '',
      adminusername: '',
      adminpassword: '',
      confirmpwd: '',
      adminname: '',
      adminmobile: '',
      adminemail: '',
      remark: '',
      aiPlatform: '',
      platforms: [],
      aiPlatformParams: '',
      models: [],
      selectedModels: [],
      loading: null,
      companyId: null,
    };
  },
  mounted() {
    this.getAiPlatformList();
    if (this.$route.query.id) {
      this.companyId = this.$route.query.id;
      this.getCompanyInfo();
      this.fetchData();
    }
  },
  methods: {
    async getCompanyInfo() {
      try {
        const {data} = await companyInfo(this.companyId);
        if (data.code === 0) {
          const company = data.data;
          this.avatarUrl = company.logo;
          this.companyname = company.companyName;
          if (company.aiPlatform) {
            this.handlePlatformChange(company.aiPlatform);
          }
          this.selectedModels = company.models.split(',');
          this.adminusername = company.adminUsername;
          this.adminpassword = company.adminPassword;
          this.confirmpwd = company.adminPassword;
          this.adminname = company.adminName;
          this.adminmobile = company.adminMobile;
          this.adminemail = company.adminEmail;
          this.remark = company.remark;
          this.aiPlatformParams = company.aiPlatformParams;
        }
      } catch (error) {
        console.error(this.$t('获取公司详情失败:'), error);
      }
    },
    async getAiPlatformList() {
      try {
        const {data} = await getAiPlatformList();
        if (data.code === 0) {
          this.platforms = data.data
        }
      } catch (error) {
        console.error(this.$t('获取AI平台列表失败:'), error);
      }
    },
    async getModels(aiPlatform) {
      try {
        const {data} = await companyModels({aiPlatform, linkCompanyId: this.companyId});
        if (data.code === 0) {
          this.models = data.data
          this.selectedModels = data.data.filter(item => item.companyLinked).map(item => item.id)
        }
      } catch (error) {
        console.error(this.$t('获取模型列表失败:'), error);
      }
    },
    
    async getAiPlatformConf(aiPlatform) {
      try {
        const {data} = await getAiPlatformConf({companyId: this.companyId, aiPlatform});
        if (data.code === 0) {
          this.aiPlatformParams = JSON.stringify(JSON.parse(data.data), null, 2)
        }
      } catch (error) {
        console.error(this.$t('获取AI平台配置模板失败:'), error);
      }
    },
    handlePlatformChange(aiPlatform) {
      this.aiPlatform = aiPlatform;
      this.getModels(aiPlatform);
      this.getAiPlatformConf(aiPlatform);
    },
    async submitForm() {
      // 必填字段校验
      const requiredFields = [
        {field: this.companyname, message: this.$t('企业名称不能为空'), scope: ['add', 'update']},
        {field: this.aiPlatform, message: this.$t('平台选择不能为空'), scope: ['add', 'update']},
        {field: this.selectedModels, message: this.$t('模型选择不能为空'), scope: ['add', 'update']},
        {field: this.adminusername, message: this.$t('管理员账号不能为空'), scope: ['add']},
        {field: this.adminpassword, message: this.$t('初始密码不能为空'), scope: ['add']},
        {field: this.confirmpwd, message: this.$t('确认密码不能为空'), scope: ['add']},
        {field: this.adminname, message: this.$t('管理员姓名不能为空'), scope: ['add']},
        {field: this.adminmobile, message: this.$t('管理员手机号不能为空'), scope: ['add']},
        {field: this.adminemail, message: this.$t('管理员邮箱不能为空'), scope: ['add']},
        {field: this.aiPlatformParams, message: this.$t('平台配置不能为空'), scope: ['add', 'update']},
      ];
      
      if (this.confirmpwd && this.confirmpwd !== this.adminpassword) {
        ElMessage({
          type: 'error',
          message: this.$t('确认密码与初始密码不一致！'),
        });
      }

      // 检查必填字段
      for (const {field, message, scope} of requiredFields) {
        if (this.companyId && scope.every(s => s !== 'update')) {
          continue;
        }
        
        if (!field || (Array.isArray(field) && field.length === 0)) {
          ElMessage({
            type: 'error',
            message,
          });
          return; // 阻止表单提交
        }
      }
      
      // 校验确认密码是否与初始密码一致
      if (this.confirmpwd !== this.adminpassword) {
        ElMessage({
          type: 'error',
          message: this.$t('确认密码与初始密码不一致！'),
        });
        return; // 阻止表单提交
      }
      // 校验平台配置是否为 JSON 格式
      let jsonMin
      try {
        jsonMin = JSON.stringify(JSON.parse(this.aiPlatformParams));
      }catch (e) {
        ElMessage({
          type: 'error',
          message: this.$t('平台配置格式错误！'),
        });
        return; // 阻止表单提交
      }
      
      // 构造表单数据
      const formData = {
        logo: this.avatarUrl,
        companyName: this.companyname,
        aiPlatform: this.aiPlatform,
        remark: this.remark,
        adminUsername: this.adminusername,
        adminPassword: this.adminpassword,
        adminName: this.adminname,
        adminMobile: this.adminmobile,
        adminEmail: this.adminemail,
        models: this.selectedModels.join(','),
        aiPlatformParams: jsonMin
      };
      
      try {
        let response;
        if (this.companyId) {
          // 编辑操作
          response = await editCompany(this.companyId, formData);
        } else {
          // 新增操作
          response = await addCompany(formData);
        }
        
        if (response.data.code === 0) {
          ElMessage({
            type: 'success',
            message: this.companyId ? this.$t('企业信息更新成功!') : this.$t('企业信息添加成功!'),
          });
          this.$router.push({name: 'Company'}); // 假设 CompanyList 是企业列表页面
        } else {
          ElMessage({
            type: 'error',
            message: this.companyId ? this.$t('企业信息更新失败!') : this.$t('企业信息添加失败!'),
          });
        }
      } catch (error) {
        console.error(this.$t('提交表单失败:'), error);
        ElMessage({
          type: 'error',
          message: this.$t('提交表单失败!'),
        });
      }
    },
    beforeUpload() {
      this.loading = ElLoading.service({
        lock: true,
        text: this.$t('Loading'),
        background: 'rgba(0, 0, 0, 0.7)',
      });
    },
    handleUploadSuccess(response, file, fileList) {
      if (this.loading) {
        this.loading.close();
      }
      if (response.code === 0) {
        this.avatarUrl = response.data.src;
        ElMessage({
          type: 'success',
          message: this.$t('文件上传成功!'),
        });
      }
    },
    handleUploadError(err, file, fileList) {
      if (this.loading) {
        this.loading.close();
      }
      ElMessage({
        type: 'error',
        message: this.$t('文件上传失败!'),
      });
    },
    deleteItem(id) {
      ElMessageBox.confirm(
        this.$t('删除该APIKEY后不能恢复，确定要删除吗？'),
        this.$t('删除确认'),
        {
          confirmButtonText: this.$t('删除'),
          cancelButtonText: this.$t('取消'),
          type: 'warning',
        },
      )
        .then(async () => {
          try {
            const {data} = await deleteSysWnApikey([id]); // 使用数组传递单个 ID
            if (data.code === 0) {
              ElMessage({
                type: 'success',
                message: this.$t('删除成功'),
              });
              this.fetchData(); // 删除后刷新数据
            } else {
              ElMessage({
                type: 'error',
                message: data.message || this.$t('删除失败，请重新操作'),
              });
            }
          } catch (error) {
            console.log(error);
            ElMessage({
              type: 'error',
              message: this.$t('删除请求失败，请稍后再试'),
            });
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: this.$t('取消删除'),
          });
        });
    },
    deleteSome() {
      const selectedIds = this.selectedItems.map(
        (item) => item.id,
      );
      
      if (selectedIds.length === 0) {
        ElMessage({
          type: 'warning',
          message: this.$t('请选择要删除的APIKEY！'),
        });
        return;
      }
      
      ElMessageBox.confirm(
        this.$t('已选择') + ' ' + selectedIds.length + ' ' + this.$t('条APIKEY数据，删除该APIKEY后不能恢复，确定要删除吗？'),
        this.$t('删除确认'),
        {
          confirmButtonText: this.$t('删除'),
          cancelButtonText: this.$t('取消'),
          type: 'warning',
        },
      )
        .then(async () => {
          try {
            const {data} = await deleteSysWnApikey(selectedIds); // 使用数组传递多个 ID
            if (data.code === 0) {
              ElMessage({
                type: 'success',
                message: this.$t('删除成功'),
              });
              this.fetchData(); // 删除后刷新数据
            } else {
              ElMessage({
                type: 'error',
                message: data.message || this.$t('删除失败，请重新操作'),
              });
            }
          } catch (error) {
            console.log(error);
            ElMessage({
              type: 'error',
              message: this.$t('删除请求失败，请稍后再试'),
            });
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: this.$t('取消删除'),
          });
        });
    },
    handleSelectionChange(selections) {
      this.selectedItems = selections;
    },
    async fetchData() {
      try {
        const {data} = await getSysWnApikey({
          companyId: this.companyId
        }); // 请求事件数据
        if (data.code === 0) {
          this.tableData = data.data.records;
          this.total = +data.data.total;
          this.pageSize = +data.data.size;
        }
      } catch (error) {
      }
    },
    
    // 翻页处理
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchData(); // 翻页时重新请求数据
    },
    // 每页显示条数变化处理
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchData(); // 每页条数变化时重新请求数据
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: calc(100% - 60px);
  background: #181818;
  box-shadow: 12px 12px 30px 0px rgba(40, 58, 44, 0.08);
  border-radius: 32px 32px 32px 32px;
  overflow: hidden;
  padding-bottom: 100px;
  
  .api-key {
    .el-button {
      transition: 0.3s ease;
      background: #303f2e;
      border-color: $color;
      
      &:hover {
        background-color: $color;
        border-color: $color;
      }
    }
  }
  
  .user {
    padding: 20px 25px;
    
    .divider {
      width: 100%;
      height: 1px;
      border-bottom: 1px solid #3B3B3B;
      margin-bottom: 26px;
    }
    
    .actions {
      .iconfont {
        font-size: 20px;
        transition: 0.3s ease;
        margin-right: 26px;
        cursor: pointer;
        
        &:hover {
          color: $color;
        }
      }
    }
    
    .label-out {
      font-weight: 400;
      font-size: 24px;
      color: #ffffff;
      line-height: 60px;
    }
    
    
    .form {
      display: flex;
      align-items: center;
      margin-bottom: 30px;
      
      .label {
        font-weight: 400;
        font-size: 18px;
        color: #FFFFFF;
        width: 200px;
        
        .require {
          color: #FF5C5C;
          margin-right: 5px;
        }
      }
    }
    
    .progress {
      margin-left: 38px;
      
      .label {
        display: flex;
        align-items: center;
        
        .dot {
          width: 12px;
          height: 12px;
          border-radius: 50%;
          background: #D8D8D8;
          border: 2px solid #D8D8D8;
          margin-right: 25px;
          position: relative;
          
          &::after {
            position: absolute;
            display: block;
            content: '';
            height: 60px;
            width: 1px;
            border-left: 1px dashed #D8D8D8;
            top: 15px;
            left: 6px;
          }
          
          &.no-line {
            &::after {
              display: none;
            }
          }
          
          &.active {
            background: #000000;
            border: 2px solid $color;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.user-upload {
  
  .avatar-upload,
  .avatar {
    width: 107px;
    height: 107px;
    background: #404040;
    border-radius: 50%;
  }
}

.user-input {
  .el-input__wrapper {
    padding: 0;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .el-input {
    width: 413px;
    
    .el-input__inner {
      width: 413px;
      box-shadow: none;
      height: 46px;
      background: #000000;
      color: #fff;
      padding: 8px 16px;
    }
  }
}
</style>
